package core.rdd.持久化;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.storage.StorageLevel;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

/**
 * checkpoint是为了不同进程可以共享数据，可以指定为HDFS的共享文件或者是本次文件夹
 *
 * checkpoint为了保证数据的安全性，如果不加cache会从头再跑一遍，再进行持久化
 * 因此在日常使用中会添在执行checkpoint之前会执行一次cache。
 */
public class Spark03_CheckPoint_A {
    public static void main(String[] args) {

        // 配置SparkConf指向你的Spark master URL
        SparkConf conf = new SparkConf()
                .setAppName("Spark03_CheckPoint_A") // 应用名称
                .setMaster("local[*]"); // 替换成你的master地址
        JavaSparkContext sc = new JavaSparkContext(conf);
        sc.setCheckpointDir("checkpoint");
        // 创建JavaSparkContext，它是与集群交互的主要入口点
        try {
            JavaRDD<String> rdd = sc.textFile("data/word.txt");


            JavaRDD<String> flatMapRdd = rdd.flatMap(new FlatMapFunction<String, String>() {
                @Override
                public Iterator<String> call(String s) throws Exception {
                    System.out.println("读取……………………………………………………………………………………………………………………………………………………………………");
                    Iterator<String> iterator = Arrays.asList(s.split(" ")).iterator();
                    return iterator;
                }
            });
            flatMapRdd.cache();
            flatMapRdd.checkpoint();

            JavaPairRDD<String, Integer> stringIntegerJavaPairRDD = flatMapRdd.mapToPair(new PairFunction<String, String, Integer>() {
                @Override
                public Tuple2<String, Integer> call(String s) throws Exception {
                    return new Tuple2<>(s, 1);
                }
            });

            System.out.println(stringIntegerJavaPairRDD.toDebugString());
//            stringIntegerJavaPairRDD.collect().forEach(System.out::println);
//
//            JavaPairRDD<Object, Iterable<String>> objectIterableJavaPairRDD = flatMapRdd.groupBy(new Function<String, Object>() {
//                @Override
//                public Object call(String v1) throws Exception {
//                    return v1;
//                }
//            });
//
//
//            objectIterableJavaPairRDD.collect().forEach(System.out::println);
        } finally {
            sc.close();
        }
    }
}
